/*
 * Copyright (C) 2011 JiangHongTiao
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package sk.lieskove.jianghongtiao.multithreaddownloader.request.converter;

import org.apache.log4j.Logger;
import sk.lieskove.jianghongtiao.multithreaddownloader.request.exceptions.OutOfRangeException;

/**
 * Date of create: May 19, 2011
 *
 * @author JiangHongTiao <jjurco.sk_gmail.com>
 * @version 2011.0519
 */
public class IntRangeIncludeConverter implements Converter {
    
    private Integer min;
    private Integer max;
    Logger log = Logger.getLogger(IntRangeIncludeConverter.class.getName());

    /**
     * Converter for checking minimal and maximal range of value. If only one bound
     * is necessary, leave second one <code>null</code>. But both of them cannot 
     * be <code>null</code> in the same time. 
     * @param min minimal value included in range
     * @param max maximal value included in range
     */
    public IntRangeIncludeConverter(Integer min, Integer max) {
        log.debug("IntRangeIncludeConverter created with values (min,max)=("+min+","+max+").");
        if(min==null && max==null){
            throw new IllegalArgumentException("Both of the values cannot be null!");
        }
        this.min = min;
        this.max = max;
    }

    @Override
    public String convert(String value) throws Exception {
        log.debug("converter IntRangeIncludeConverter used with (min,max)=("+min+","+max+") for value: "+value);
        Integer val = Integer.parseInt(value);
        if((min!=null) && (val<min)){
            throw new OutOfRangeException("Value '"+value+"' is lower than minimal value: " + min);
        }
        if((max!=null) && (val>max)){
            throw new OutOfRangeException("Value '"+value+"' is greather than maximal value: " + max);
        }
        return value;
    }
    
}
